<?php
class Model_Colibri_Page extends Model
{
	private $_page = array();
	private $_tree = array();

	public function __construct()
	{
		$pages = DB::select()->from('pages')->order_by('parent_id')->order_by('weight')->execute()->as_array();
		foreach ($pages as $page)
		{
			$page_id = $page['id'];
			$page['current'] = false;
			unset($page['id']);
			$this->_page[$page_id] = $page;
		}
	}

	public function request($url = '', $default = 1)
	{

		if (empty($url)) {
			$this->_page[$default]['current'] = true;
			$request = $this->_page[$default];
		}
		else
		{
			$uri_arr = explode('/', $url);
			$page_alias = end($uri_arr);
			$needle = array('alias' => $page_alias, 'level' => (sizeof($uri_arr) - 1));
			$index = $this->search_page($needle, $this->_page);
			if ($index)
			{
				$this->_page[$index]['current'] = true;
				$request = $this->_page[$index];
			}
			else
			{
				$request = array('title' => 'Page not found', 'template' => 'err_404.tpl', 'keyword' => '', 'description' => '');
			}
		}

		return $request;
	}

	public function tree()
	{
		$tree = $this->_page;
		foreach ($tree as $k => $page)
		{
			if ($page['parent_id'] != 0)
			{
				$tree[$page['parent_id']]['child'][] = $tree[$k];
				unset($tree[$k]);
			}
		}
		$this->_tree = $tree;
		return $this->_tree;
	}

	public function set($key, $value = "")
	{
		if (array_key_exists($key, $this->_settings))
		{
			DB::update('pages')->set(array('value' => $value))->where('name', '=', $key)->execute();
		}
		else
		{
			DB::insert('pages', array('name', 'value'))->values(array($key, $value))->execute();
		}
		$this->_settings[$key] = $value;
	}

	private function search_page($searched, $pages)
	{
		if (empty($searched) || empty($pages))
		{
			return false;
		}

		foreach ($pages as $key => $value)
		{
			$exists = true;
			foreach ($searched as $skey => $svalue)
			{
				$exists = ($exists && isset($pages[$key][$skey]) && $pages[$key][$skey] == $svalue);
			}
			if ($exists)
			{
				return $key;
			}
		}
	}
}